<?php

/**
 * 用户ajax请求处理
 */

include '../includes/fun.global.php';
include_once(SYSTEM_ROOT . "extend/GoodsImage.php");
include_once(SYSTEM_ROOT . "fun.admin.php");
include_once(SYSTEM_ROOT . "extend/VerificationCode.php");

use extend\ImgThumbnail;
use extend\UserConf;
use lib\Hook\Hook;
use Medoo\DB\SQL;
use sms\sms_operation;

@header('Content-Type: application/json; charset=UTF-8');
$USERDATA = login_data::user_data();
if ($conf['ShutDownUserSystem'] == -1) dies(-1, $conf['ShutDownUserSystemCause']);
switch ($_QET['act']) {
    case 'user_set': //修改用户信息
        if ($USERDATA == false) dies(-1, '请先登陆！');
        if (empty($_QET['mobile']) || empty($_QET['name']) || empty($_QET['qq']) || empty($_QET['username'])) dies(-1, '请填写完整！');
        if (strlen((int)$_QET['mobile']) <> 11) dies(-1, '手机号输入有误！');

        preg_match('/^[a-zA-Z0-9]{6,18}+$/u', $_QET['username'], $arr_pr);
        if (empty($arr_pr[0])) dies(-1, '登陆账号只可为英文或数字,并且长度要大于6小于18位！');

        preg_match('/^[0-9]{6,12}+$/u', $_QET['qq'], $arr_pr);
        if (empty($arr_pr[0])) dies(-1, 'QQ号码格式不正确！');

        if ($_QET['username'] == $_QET['password'] && !empty($_QET['password'])) dies(-1, '账号和密码不能一样！');

        preg_match('/^[a-zA-Z0-9]{6,18}+$/u', $_QET['password'], $arr_pr);
        if (empty($arr_pr[0]) && !empty($_QET['password'])) dies(-1, '登陆密码只可为英文或数字,并且长度要大于6小于18位！');

        $DB = SQL::DB();

        $Res = $DB->select('user', '*', [
            'OR' => [
                'username' => $_QET['username'],
                'qq' => $_QET['qq'],
                'mobile' => $_QET['mobile'],
            ],
            'id[!]' => $USERDATA['id'],
        ]);


        foreach ($Res as $value) {
            if ($value['username'] == $_QET['username']) dies(-1, '账号[' . $_QET['username'] . ']已经被Ta人绑定过了,换个账号吧~');
            if ($value['qq'] == $_QET['qq']) dies(-1, 'QQ[' . $_QET['qq'] . ']已经被Ta人绑定过了,换个QQ吧~');
            if ($value['mobile'] == $_QET['mobile']) dies(-1, '手机号[' . $_QET['mobile'] . ']已经被Ta人绑定过了,换个手机号吧~');
        }

        $Res = $DB->update('user', [
            'mobile' => $_QET['mobile'],
            'qq' => $_QET['qq'],
            'username' => $_QET['username'],
            'password' => (!empty($_QET['password']) ? md5($_QET['password']) : $USERDATA['password']),
            'name' => $_QET['name'],
        ], ['id' => $USERDATA['id']]);

        if ($Res) {
            userlog('修改信息', '用户[' . $USERDATA['id'] . ']于' . $date . '修改了个人信息！', $USERDATA['id'], '0');
            if ($_QET['username'] <> $USERDATA['username']) {
                setcookie("THEKEY", null, time() - 3600 * 12 * 15, '/');
                dies(1, '修改成功，由于修改了账号，您需要重新登陆！');
            } else dies(1, '修改成功！');
        } else dies(-1, '修改失败!');

        dier($_QET);
        break;
    case 'login_account': //账号密码登陆
        if ($USERDATA <> false) dies(1, '您已登陆！');

        if ($conf['AccountPasswordLogin'] <> 1) dies(-1, '当前站点未开启账号登陆,请使用其他登陆方式登陆！');

        if (empty($_QET['user']) || empty($_QET['pass']) || empty((int)$_QET['vercode'])) dies(-1, '请填写完整！');
        preg_match('/^[a-zA-Z0-9]{6,18}+$/u', $_QET['user'], $arr_pr);
        if (empty($arr_pr[0])) dies(-1, '账号输入有误！');
        if (empty($_SESSION['Login_vc']) || $_SESSION['Login_vc'] <> md5((int)$_QET['vercode'] . href())) dies(-2, '验证码有误！');

        $DB = SQL::DB();

        $Res = $DB->get('user', '*', [
            'username' => $_QET['user'],
            'password' => md5($_QET['pass']),
            'LIMIT' => 1,
        ]);

        if (!$Res) dies(-1, '用户不存在或账号密码错误！');

        if ($Res['state'] != 1) dies(-1, '您的账号已被禁封，无法登陆');

        userlog('后台登陆', '用户于' . $date . '通过手机号成功登陆后台！', $Res['id'], '0');

        setcookie("THEKEY", $Res['user_idu'], time() + 3600 * 12 * 15, '/');
        query::OrderUser($Res['id']);

        Hook::execute('UserLogin', [
            'name' => $Res['name'],
            'id' => $Res['id']
        ]);
        include_once(SYSTEM_ROOT . "extend/GoodsCart.php");
        \extend\GoodsCart::UserCookieDer($Res['id']);
        dies(1, '登陆成功，[' . $Res['name'] . ']欢迎回来！');
        break;
    case 'login_register': //用户注册！

        if ($USERDATA <> false) dies(1, '您已登陆！');

        if ($conf['AccountPasswordLogin'] <> 1) dies(-2, '当前站点未开启账号注册,请使用其他登陆方式登陆！');

        if (empty((int)$_QET['qq']) || empty($_QET['name']) || empty((int)$_QET['mobile']) || empty($_QET['username']) || empty($_QET['password']) || empty((int)$_QET['vercode'])) dies(-1, '请填写完整！');
        if (empty($_SESSION['Login_res']) || $_SESSION['Login_res'] <> md5((int)$_QET['vercode'] . href())) {
            $_SESSION['Login_res'] = null;
            dies(-2, '验证码有误！');
        } else {
            $_SESSION['Login_res'] = null;
        }

        preg_match('/^[a-zA-Z0-9]{6,18}+$/u', $_QET['username'], $arr_pr);
        if (empty($arr_pr[0])) dies(-2, '登陆账号只可为英文或数字,并且长度要大于6小于18位！');

        preg_match('/^[a-zA-Z0-9]{6,18}+$/u', $_QET['password'], $arr_pr);
        if (empty($arr_pr[0])) dies(-2, '登陆密码只可为英文或数字,并且长度要大于6小于18位！');

        preg_match('/^[0-9]{6,12}+$/u', $_QET['qq'], $arr_pr);
        if (empty($arr_pr[0])) dies(-2, 'QQ号码格式不正确！');

        if ($_QET['username'] == $_QET['password']) dies(-2, '账号和密码不能一样！');

        if (strlen((int)$_QET['mobile']) <> 11) dies(-2, '手机号输入有误！');

        /**
         * 验证数据层
         */

        $DB = SQL::DB();

        $Res = $DB->select('user', '*', [
            'OR' => [
                'username' => $_QET['username'],
                'qq' => $_QET['qq'],
                'mobile' => $_QET['mobile'],
            ]
        ]);


        foreach ($Res as $value) {
            if ($value['username'] == $_QET['username']) dies(-2, '账号[' . $_QET['username'] . ']已经被Ta人注册过了,换个账号吧~');
            if ($value['qq'] == $_QET['qq']) dies(-2, 'QQ[' . $_QET['qq'] . ']已经被Ta人绑定过了,换个QQ吧~');
            if ($value['mobile'] == $_QET['mobile']) dies(-2, '手机号[' . $_QET['mobile'] . ']已经被Ta人绑定过了,换个手机号吧~');
        }

        /**
         * 注册开始
         */

        $uid_md = md5($_SESSION['Login_res'] . time() . rand(10000, 999999));

        $Uty = UserConf::judge();
        if ($Uty == false) {
            $Uty = 0;
        } else $Uty = $Uty['id'];

        $Data = [
            'grade' => $conf['userdefaultgrade'],
            'user_idu' => $uid_md,
            'currency' => 0,
            'ip' => userip(),
            'image' => 'http://q4.qlogo.cn/headimg_dl?dst_uin=' . $_QET['qq'] . '&spec=100',
            'name' => $_QET['name'],
            'state' => 1,
            'recent_time' => $date,
            'found_date' => $date,
            'qq' => $_QET['qq'],
            'mobile' => $_QET['mobile'],
            'username' => $_QET['username'],
            'password' => md5($_QET['password']),
        ];

        if (empty($_COOKIE['INVITED_STATUS'])) {
            $Data['superior'] = $Uty;
        } else {
            $C = $DB->get('user', '*', ['id' => $_COOKIE['INVITED_STATUS'], 'LIMIT' => 1]);
            if ($C) {
                $GETTE = 1;
                $Data['superior'] = $_COOKIE['INVITED_STATUS'];
            } else {
                $Data['superior'] = $Uty;
                setcookie("INVITED_STATUS", null, time() - 3600 * 12 * 15, '/');
            }
        }

        $Res = $DB->insert('user', $Data);

        if ($Res) {
            $ID = $DB->id();
            $IP = userip();
            $GETID = $DB->get('user', '*', ['id' => $ID]);
            if ($GETTE == 1) {
                $FTR = $DB->get('invite', '*', ['ip' => $IP, 'LIMIT' => 1]);
                if (!$FTR) {
                    $award = $conf['award'];
                    userlog('邀请奖励', '恭喜您成功邀请到用户[' . $_QET['name'] . ']特奖励您' . $award . $conf['currency'] . '！,再接再厉哦', $_COOKIE['INVITED_STATUS'], $award);
                    @$DB->insert('invite', [
                        'uid' => $_COOKIE['INVITED_STATUS'],
                        'invitee' => $ID,
                        'award' => $award,
                        'ip' => $IP,
                        'creation_time' => $date,
                    ]);
                    Hook::execute('UserInvite', [
                        'id' => $_COOKIE['INVITED_STATUS'],
                        'yid' => $ID,
                        'num' => $award
                    ]);
                } else {
                    userlog('失败邀请', '系统判断您的邀请对象：[' . $_QET['name'] . ']已经在其他账号接收过邀请,无法奖励！,请邀请真实用户！', $_COOKIE['INVITED_STATUS'], 0);
                }
            }

            if ($GETID) query::OrderUser($ID);
            include_once(SYSTEM_ROOT . "extend/GoodsCart.php");
            if ($GETID) \extend\GoodsCart::UserCookieDer($ID);

            setcookie("THEKEY", $uid_md, time() + 3600 * 12 * 15, '/');
            Hook::execute('UserRegister', [
                'id' => $GETID['id'],
                'name' => $GETID['name']
            ]);
            dies(1, '恭喜你,注册成功，欢迎你加入这个大家庭！');
        } else dies(-2, '注册失败!');

        break;
    case 'VerificationCode': //创建登陆二维码图片
        if (empty($_QET['n'])) dies(-1, '请填写完整！');
        $code = '';
        $num = 5;
        for ($i = 0; $i < $num; $i++) {
            $code .= rand(1, 9);
        }
        $_SESSION[$_QET['n']] = md5($code . href());
        \extend\VerificationCode::RandomVerificationCode($code, $_QET['n'], $num);
        break;
    case 'prevent':
        if ($conf['userdomaintype'] == 1) {
            $url = is_https(false) . $USERDATA['domain'];
        } else $url = is_https(false) . href() . '?t=' . $USERDATA['domain'];
        if ($conf['prevent_switch'] == 1) {
            dies(1, reward::prevent($url, 2));
        } else dies(1, $url);
        break;
    case 'user_pay':
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        if (empty((float)$_QET['money']) || empty($_QET['type'])) dies(-1, '请提交完整哦!');
        $data_arr = reward::user_payet($_QET['money'], $_QET['type'], $USERDATA);
        die($data_arr);
        break;
    case 'add_token': #生成
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        $token = md5($USERDATA['token'] . rand(10000, 9999999999) . time());
        $a = $DB->query("UPDATE `sky_user` SET `token`='$token' WHERE  (`id`='{$USERDATA['id']}')");
        if ($a) {
            die(json_encode(['code' => 1, 'msg' => 'token更新成功', 'token' => $token]));
        } else dies(-1, 'token更新失败');
        break;
    case 'ip_data':
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        if (empty($_QET['ip_data'])) dies(-1, '请填写完整');
        $Ip = implode('|', $_QET['ip_data']);
        $DB = SQL::DB();
        $a = $DB->update('user', [
            'ip_white_list' => $Ip
        ], [
            'id' => $USERDATA['id']
        ]);
        if ($a) {
            die(json_encode(['code' => 1, 'msg' => '设置成功', 'ip_data' => $Ip]));
        } else dies(-1, '设置失败');
        break;
    case 'user_updating':
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        header("Content-Type:text/html;charset=utf8");
        echo login_data::user_reception($_QET);
        break;
    case 'connected':
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        die(login_data::login('/user/ajax.php?act=user_updating'));
        break;
    case 'Send_verification_code':
        $num = $conf['usersmsbinding'];
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        if (empty((int)$_QET['mobile'])) dies(-1, '请将手机号填写完整！');
        $count = $DB->count("SELECT count(*) FROM `sky_journal` WHERE `name` = '短信验证' AND `date` > '$times' AND `uid` = '{$USERDATA['id']}'  "); //今日发信次数
        if ($count >= $num) dies(-1, '今日短信验证次数已经耗尽,每日仅可发送' . $num . '次验证码！');
        if ($USERDATA['mobile'] == $_QET['mobile']) dies(-1, '新手机号不能和旧的相同！');
        $vr = $DB->get_row("SELECT * FROM `sky_user` WHERE `mobile` = '{$_QET['mobile']}' AND `id`!='{$_QET['id']}' ");
        if ($vr) dies(-1, '此手机号已被用户：' . $vr['id'] . '绑定！');
        $sms = new sms_operation(href(), $accredit['token'], 1);
        $_SESSION['VerifyCode'] = $sms->randString();
        $_SESSION['Mobile'] = (int)$_QET['mobile'];
        $arr = $sms->sum_send($_SESSION['VerifyCode'], $_SESSION['Mobile']);
        if ($arr['code'] == 1) {
            userlog('短信验证', '用户于' . $date . ' 为绑定手机号[' . $_SESSION['Mobile'] . '] 发送了短信验证码!', $USERDATA['id']);
            dier($arr);
        } else dier($arr);
        break;
    case 'Send_verification':
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        if (empty($_SESSION['VerifyCode']) || empty($_SESSION['Mobile'])) dies(-1, '请先发送验证码！');
        if (empty((int)$_QET['code'])) dies(-1, '请填写完整！');
        if ((int)$_SESSION['VerifyCode'] <> (int)$_QET['code']) dies(-2, '验证码有误,请核对后再输入！');
        $DB = SQL::DB();
        $re = $DB->update('user', [
            'mobile' => $_SESSION['Mobile']
        ], [
            'id' => $USERDATA['id']
        ]);
        if ($re) {
            userlog('手机绑定', '用户于' . $date . '将绑定手机号修改为：' . $_SESSION['Mobile'], $USERDATA['id']);
            dies(1, '手机号绑定成功<br>您以后可以用手机号：' . $_SESSION['Mobile'] . '登陆后台了！!');
        } else dies(-1, '绑定失败！' . $DB->error());
        break;
    case 'configuration_save':
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        if ($conf['userleague'] <> 1) dies(-1, '当前商城未开启用户加盟权限！');
        if ($USERDATA['grade'] < $conf['userleaguegrade']) dies(-1, '您当前的等级无法开通店铺,请先去提升等级！');
        if (empty($_QET['type'])) dies(-1, '请填写完整！');

        $DB = SQL::DB();

        if ($USERDATA['configuration'] == '') {
            $configuration_arr = [];
        } else $configuration_arr = config::common_unserialize($USERDATA['configuration']);
        switch ($_QET['type']) {
            case 'domain':
                if ($conf['userdomaintype'] == 1) {
                    if (empty($_QET['domain']) || empty($_QET['prefix'])) dies(-1, '请填写完整！');
                    preg_match('/^[a-zA-Z0-9]{2,6}+$/u', $_QET['prefix'], $arr_pr);
                    if (empty($arr_pr[0])) dies(-1, '前缀只可为a-Z,0-9的字符串<br>并且前缀长度必须在2-6之间！');
                    $domain = $_QET['prefix'] . '.' . $_QET['domain'];
                    if (in_array($_QET['prefix'], explode(',', $conf['userdomainretain']))) dies(-1, '此域名前缀不可使用，换一个吧！');

                    if ($DB->get('user', ['domain'], ['domain' => $domain, 'id[!]' => $USERDATA['id']])) dies(-1, '域名（' . $domain . '）已经被他人绑定过了，换一个吧');

                    if ($USERDATA['domain'] == '') {
                        $re = $DB->update('user', [
                            'domain' => $domain
                        ], [
                            'id' => $USERDATA['id']
                        ]);
                        $money = 0;
                    } else {
                        $money = $conf['userdomainsetmoney'];
                        if (explode('.', $USERDATA['domain'])[0] == $_QET['prefix']) $money = 0;
                        if ($USERDATA['money'] < $money) dies(-1, '余额不足,无法完成域名换绑！<br>还差' . ($money - $USERDATA['money']) . '元,快去充值吧');

                        $re = $DB->update('user', [
                            'domain' => $domain,
                            'money[-]' => $money
                        ], [
                            'id' => $USERDATA['id']
                        ]);
                    }
                    if ($re) {
                        userlog('域名绑定', '您在店铺管理界面绑定了域名：' . $domain, $USERDATA['id'], $money);
                        dies(1, '店铺域名绑定成功！<br>您以后可以用域名：' . $domain . '<br>访问您的店铺首页了哦！');
                    } else dies(-1, '店铺域名绑定失败,请联系管理员处理！');
                } else {
                    if (empty($_QET['prefix'])) dies(-1, '请填写完整！');
                    preg_match('/^[a-zA-Z0-9]{2,6}+$/u', $_QET['prefix'], $arr_pr);
                    if (empty($arr_pr[0])) dies(-1, '后缀小尾巴只可为a-Z,0-9的字符串<br>并且前缀长度必须在2-6之间！');
                    $domain = $_QET['prefix'];
                    if (in_array($_QET['prefix'], explode(',', $conf['userdomainretain']))) dies(-1, '此域名小尾巴不可使用，换一个吧！');
                    $vs = $DB->get('user', ['domain'], ['domain' => $domain, 'id[!]' => $USERDATA['id']]);
                    if ($vs) dies(-1, '域名小尾巴（' . $domain . '）已经被他人绑定过了，换一个吧');
                    if ($USERDATA['domain'] == '') {
                        $re = $DB->update('user', [
                            'domain' => $domain,
                        ], [
                            'id' => $USERDATA['id']
                        ]);
                        $money = 0;
                    } else {
                        $money = $conf['userdomainsetmoney'];
                        if (explode('.', $USERDATA['domain'])[0] == $_QET['prefix']) $money = 0;
                        if ($USERDATA['money'] < $money) dies(-1, '余额不足,无法完成域名换绑！<br>还差' . ($money - $USERDATA['money']) . '元,快去充值吧');
                        $re = $DB->update('user', [
                            'domain' => $domain,
                            'money[-]' => $money
                        ], [
                            'id' => $USERDATA['id']
                        ]);
                    }
                    if ($re) {
                        userlog('域名绑定', '您在店铺管理界面绑定了域名小尾巴：' . $domain, $USERDATA['id'], $money);
                        dies(1, '店铺域名绑定成功！<br>您以后可以用域名：' . is_https(false) . href() . '?t=' . $domain . '<br>访问您的店铺首页了哦！');
                    } else dies(-1, '店铺域名绑定失败,请联系管理员处理！');
                }
                break;
            case 'template':
                if ($USERDATA['grade'] < $conf['usergradetem']) dies(-1, '您当前等级无法装修店铺,请先去提升等级吧！');
                $template_arr = for_dir("../template/");
                if (!in_array($_QET['template'], $template_arr) && $_QET['template'] != -1 && $_QET['template'] != -2) dies(-1, 'PC端模板[' . $_QET['template'] . ']不存在');
                if (!in_array($_QET['template_m'], $template_arr) && $_QET['template_m'] != -1) dies(-1, '移动端模板[' . $_QET['template_m'] . ']不存在');
                if (!in_array($_QET['background'], ['1', '2', '3', '4'])) dies(-1, '背景序列号不存在!');
                $configuration_arr = array_merge($configuration_arr, [
                    'template' => $_QET['template'],
                    'template_m' => $_QET['template_m'],
                    'background' => $_QET['background'],
                    'banner' => $_QET['banner'],
                ]);
                $configuration_arr = serialize($configuration_arr);
                break;
            case 'webset':
                if ($USERDATA['grade'] < $conf['usergradenotice']) dies(-1, '您当前等级无法配置店铺基础信息,请先去提升等级吧！');

                if (empty((int)$_QET['award']) || empty((int)$_QET['Signin'])) dies(-1, '请填写完整!');

                $award = $DB->get('config', '*', ['K' => 'award'])['V'];
                $Signin = $DB->get('config', '*', ['K' => 'Signin'])['V'];

                if (!$award || !$Signin) dies(-1, '主站数据获取失败！');
                if ((int)$_QET['award'] > (int)$award) dies(-1, '邀请奖励不可高于主站哦<br>主站奖励为:' . $award . '!');
                if ((int)$_QET['Signin'] > (int)$Signin) dies(-1, '签到奖励不可高于主站哦<br>主站奖励为:' . $Signin . '!');

                $configuration_arr = array_merge($configuration_arr, [
                    'sitename' => $_QET['sitename'],
                    'keywords' => $_QET['keywords'],
                    'description' => $_QET['description'],
                    'kfqq' => $_QET['kfqq'],
                    'Communication' => $_QET['Communication'],
                    'award' => $_QET['award'],
                    'Signin' => $_QET['Signin'],
                    'currency' => $_QET['currency'],
                    'ForcedLanding' => $_QET['ForcedLanding'],
                    'GoodsRecommendation' => $_QET['GoodsRecommendation'],
                    'YzfSign' => ($_QET['YzfSign'] == '' ? -1 : $_QET['YzfSign']),
                    'CartState' => ($_QET['CartState'] == 1 ? 1 : 2),
                    'DynamicMessage' => $_QET['DynamicMessage'],
                    'ServiceImage' => $_QET['ServiceImage'],
                    'ServiceTips' => $_QET['ServiceTips'],
                    'SimilarRecommend' => ($_QET['SimilarRecommend'] == 1 ? 1 : -1),
                ]);
                $configuration_arr = serialize($configuration_arr);
                break;
            case 'notice':
                if ($USERDATA['grade'] < $conf['usergradenotice']) dies(-1, '您当前等级无法配置店铺公告哦,请先去提升等级吧！');
                $configuration_arr = array_merge($configuration_arr, [
                    'notice_top' => base64_encode($_QET['notice_top']),
                    'notice_check' => base64_encode($_QET['notice_check']),
                    'notice_bottom' => base64_encode($_QET['notice_bottom']),
                    'PopupNotice' => base64_encode($_QET['PopupNotice']),
                ]);
                $configuration_arr = serialize($configuration_arr);
                break;
            default:
                dies(-1, '未知访问');
                break;
        }

        $re = $DB->update('user', [
            'configuration' => $configuration_arr,
        ], [
            'id' => $USERDATA['id']
        ]);
        if ($re) {
            userlog('更新数据', '用户更新了加盟站点数据！', $USERDATA['id'], '0');
            dies(1, '数据保存成功！');
        } else dies(-1, '数据保存失败！');
        break;
    case 'WithdrawDeposit':
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        if ($conf['userdeposit'] <> 1) dies(-1, '当前站点未开启提现功能！');
        if ($USERDATA['grade'] < $conf['userdepositgrade']) dies(-1, '您当前等级无法使用提现功能,请先去提升等级吧！');
        $arr_type = explode(',', $conf['userdeposittype']);
        if ($_QET['type'] == 'alipay' && $arr_type[0] <> 1) dies(-1, '当前支付宝提现方式未开启！');
        if ($_QET['type'] == 'wxpay' && $arr_type[1] <> 1) dies(-1, '当前微信提现方式未开启！');
        if ($_QET['type'] == 'qqpay' && $arr_type[2] <> 1) dies(-1, '当前QQ提现方式未开启！');
        if ((float)$_QET['money'] < $conf['userdepositmin']) dies(-1, '最低提现金额为' . $conf['userdepositmin'] . '元,提现条件未满足！');
        if ((float)$_QET['money'] > $USERDATA['money']) dies(-1, '余额不足,提现条件未满足！');
        $timehtm = md5($USERDATA['id'] . '小储云');
        $images = ROOT . '/assets/img/withdraw/' . $timehtm . '/' . $USERDATA['id'] . '.png';
        if (!file_exists($images)) dies(-1, '请先上传收款二维码！');
        $moneys = (float)$_QET['money'];

        $DB = SQL::DB();

        $res = $DB->update('user', [
            'money[-]' => $moneys,
        ], [
            'id' => $USERDATA['id']
        ]);

        $re = $DB->insert('withdrawal', [
            'type' => $_QET['type'],
            'name' => $_QET['name'],
            'account_number' => $_QET['account_number'],
            'uid' => $USERDATA['id'],
            'remarks' => $_QET['remarks'],
            'money' => $_QET['money'],
            'addtime' => $date,
        ]);
        if ($res && $re) {
            userlog('余额提现', '您于' . $date . '进行了提现处理操作,提现金额为：' . $moneys, $USERDATA['id'], $moneys);
            Hook::execute('WithdrawNew', [
                'image' => $images,
                'type' => $_QET['type'],
                'name' => $_QET['name'],
                'account_number' => $_QET['account_number'],
                'uid' => $USERDATA['id'],
                'remarks' => $_QET['remarks'],
                'money' => $_QET['money'],
                'addtime' => $date,
            ]);
            dies(1, '提现请求成功');
        } else dies(-1, '提现请求失败,请联系管理员处理！');
        break;
    case 'image_content': #编辑器专用
        unset($_QET['act']);
        $ImageArr = [];
        foreach ($_QET as $key => $value) {
            if ($value['type'] <> 'image/png' && $value['type'] <> 'image/gif' && $value['type'] <> 'image/jpeg') dies(-1, '只可上传png/jpg/gif类型的图片文件！');
            $timehtm = date('Ymd');
            mkdirs("../assets/img/image/" . $timehtm . '/');

            $ImageName = 'YmdHis' . rand(100000, 999999);
            switch ($value['type']) {
                case 'image/png':
                    $ImageName .= '.png';
                    break;
                case 'image/gif':
                    $ImageName .= '.gif';
                    break;
                case 'image/jpeg':
                    $ImageName .= '.jpeg';
                    break;
                default:
                    $ImageName .= '.png';
                    break;
            }

            move_uploaded_file($value["tmp_name"], '../assets/img/image/' . $timehtm . '/' . $ImageName);
            $images = '/assets/img/image/' . $timehtm . '/' . $ImageName;
            new ImgThumbnail(ROOT . $images, $conf['compression'], ROOT . $images, 2);
            $ImageArr[] = ['src' => $images, 'size' => $value['size'] / 1000 . 'kb', 'name' => $value["name"]];
        }
        dier([
            'code' => 1,
            'msg' => '图片上传成功,本次共成功上传' . count($ImageArr) . '张图片',
            'SrcArr' => $ImageArr,
        ]);
        break;
    case 'image_up': #上传图片
        $image = explode('.', $_QET["file"]["name"]);
        if ($_QET["file"]['type'] <> 'image/png' && $_QET["file"]['type'] <> 'image/gif' && $_QET["file"]['type'] <> 'image/jpeg') dies(-1, '只可上传png/jpg/gif类型的图片文件！');
        $timehtm = date('Ymd');
        mkdirs("../assets/img/image/" . $timehtm . '/');
        $ImageName = 'YmdHis' . rand(100000, 999999);
        switch ($_QET["file"]['type']) {
            case 'image/png':
                $ImageName .= '.png';
                break;
            case 'image/gif':
                $ImageName .= '.gif';
                break;
            case 'image/jpeg':
                $ImageName .= '.jpeg';
                break;
            default:
                $ImageName .= '.png';
                break;
        }
        move_uploaded_file($_QET["file"]["tmp_name"], '../assets/img/image/' . $timehtm . '/' . $ImageName);
        $images = '/assets/img/image/' . $timehtm . '/' . $ImageName;
        new ImgThumbnail(ROOT . $images, $conf['compression'], ROOT . $images, 2);
        echo json_encode(array('code' => 0, 'msg' => '上传成功,上传的图片大小为：' . $_QET['file']['size'] / 1000 . 'kb', 'src' => $images));
        break;
    case 'DoGatheringFigure':
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        if ($conf['userdeposit'] <> 1) dies(-1, '当前站点未开启提现,无法上传收款图！');
        if ($USERDATA['grade'] < $conf['userdepositgrade']) dies(-1, '您当前等级无法使用提现功能,请先去提升等级吧！');
        if ($_QET["file"]['type'] <> 'image/png' && $_QET["file"]['type'] <> 'image/gif' && $_QET["file"]['type'] <> 'image/jpeg') dies(-1, '只可上传png/jpg/gif类型的图片文件！');
        $image = explode('.', $_QET["file"]["name"]);
        $timehtm = md5($USERDATA['id'] . '小储云');
        mkdirs("../assets/img/withdraw/" . $timehtm . '/');
        $image = $USERDATA['id'] . '.png';
        move_uploaded_file($_QET["file"]["tmp_name"], '../assets/img/withdraw/' . $timehtm . '/' . $image);
        $images = '/assets/img/withdraw/' . $timehtm . '/' . $image;
        new ImgThumbnail(ROOT . $images, $conf['compression'], ROOT . $images, 2);
        dier(['code' => 0, 'msg' => '上传成功,上传的收款码大小为：' . $_QET['file']['size'] / 1000 . 'kb', 'src' => $images . '?time=' . time()]);
        break;
    case 'withdraw_deposit':
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        if ($conf['userdeposit'] <> 1) dies(-1, '当前站点未开启提现功能！');
        if ($USERDATA['grade'] < $conf['userdepositgrade']) dies(-1, '您当前等级无法使用提现功能,请先去提升等级吧！');
        $page = ((int)$_GET['page'] - 1) * (int)$_GET['limit'];
        $limit = (int)$_GET['limit'];
        $data = $DB->query("SELECT * FROM `sky_withdrawal` WHERE `uid` = '{$USERDATA['id']}' order by id desc limit $page,$limit ");
        $count = $DB->count("SELECT count(*) FROM sky_withdrawal WHERE `uid` = '{$USERDATA['id']}' ");
        $data_arr = [];
        while ($re = $DB->fetch($data)) {
            $re['arrival_amount'] = round($re['money'] - (($conf['userdepositservice'] / 100) * $re['money']), 2);
            $data_arr[] = $re;
        }
        dier([
            'code' => 0,
            'msg' => '数据获取成功',
            'count' => $count,
            'data' => $data_arr
        ]);
        break;
    case 'Tickets': //工单管理
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        if (!isset($_QET['type'])) dies(-1, '请填写完整');
        $DB = SQL::DB();
        switch ($_QET['type']) {
            case 'list':
                if ($_QET['state'] == 'all') {
                    $List = $DB->select('tickets', ['id', 'name', 'class', 'state', 'addtime', 'grade', 'type'], ['uid' => $USERDATA['id'], 'ORDER' => ['id' => 'DESC']]);
                } else {
                    $List = $DB->select('tickets', ['id', 'name', 'class', 'state', 'addtime', 'grade', 'type'], ['uid' => $USERDATA['id'], 'state' => $_QET['state'], 'ORDER' => ['id' => 'DESC']]);
                }
                dier([
                    'code' => 1,
                    'msg' => '工单列表获取成功',
                    'data' => $List,
                ]);
                break;
            case 'details': //工单详情
            case 'Supplementary': //补充内容
            case 'Finish': //完结工单
            case 'Grade': //评分
                $Tickets = $DB->get('tickets', '*', ['id' => $_QET['id'], 'uid' => $USERDATA['id']]);
                if (!$Tickets) dies(-1, '订单不存在！');
                if ($Tickets['message'] == '') {
                    $Data = [];
                } else {
                    $Data = \config::common_unserialize($Tickets['message']);
                }
                if ($_QET['type'] == 'details') {
                    dier([
                        'code' => 1,
                        'msg' => '数据获取成功',
                        'data' => $Data,
                        'class' => $Tickets['class'],
                        'time' => $Tickets['timetips'],
                        'order' => ($Tickets['order'] == null ? '无相关订单' : $Tickets['order']),
                        'state' => $Tickets['state'],
                        'grade' => $Tickets['grade'],
                        'count' => count($Data),
                        'type' => $Tickets['type'],
                    ]);
                } else if ($_QET['type'] == 'Supplementary') {
                    if ($Tickets['type'] == 4) dies(-1, '此工单已经关闭,请重新创建新的工单！');
                    if ($Tickets['type'] >= 3 || $Tickets['state'] == 3) dies(-1, '工单已完结,若要提交内容请创建新的工单!');

                    $Data = array_merge($Data, [
                        $date => [
                            'type' => 1,
                            'content' => $_QET['content'],
                        ]
                    ]);

                    $Res = $DB->update('tickets', [
                        'message' => $Data,
                        'type' => 1,
                    ], [
                        'id' => $_QET['id'],
                        'uid' => $USERDATA['id'],
                    ]);
                    if ($Res) {
                        Hook::execute('WorkOrderReply', [
                            'identity' => $USERDATA['id'],
                            'content' => $_QET['content'],
                            'id' => $_QET['id']
                        ]);
                        dies(1, '工单信息补充成功！');
                    } else dies(-1, '工单信息补充失败');
                } else if ($_QET['type'] == 'Finish') {
                    $Res = $DB->update('tickets', [
                        'state' => 1,
                        'type' => 3,
                        'endtime' => $date,
                    ], [
                        'id' => $_QET['id'],
                        'uid' => $USERDATA['id'],
                    ]);
                    if ($Res) {
                        if ($Tickets['order'] <> '不选择相关订单') {
                            @$DB->update('order', ['state' => 1], ['order' => $Tickets['order']]);
                        };
                        userlog('完结工单', '用户将工单[' . $_QET['id'] . ']的状态设置为已完结状态', $USERDATA['id'], 0);
                        Hook::execute('WorkOrderEnd', [
                            'identity' => $USERDATA['id'],
                            'id' => $_QET['id']
                        ]);
                        dies(1, '工单[' . $_QET['id'] . ']成功结单,若有其他问题可再创建工单哦！');
                    } else dies(-1, '结单失败！');
                } else if ($_QET['type'] == 'Grade') {
                    if ($Tickets['grade'] <> '') dies(-1, '此工单无法评分,条件不足！');
                    $Res = $DB->update('tickets', [
                        'grade' => (int)$_QET['n'],
                    ], [
                        'id' => $_QET['id'],
                        'uid' => $USERDATA['id'],
                    ]);
                    if ($Res) {
                        dies(1, '工单[' . $_QET['id'] . ']成功打分成功,感谢您的支持！');
                    } else dies(-1, '打分失败！');
                }
                break;
            case 'New': //新建工单
                $TicketsClass = explode(',', $conf['TicketsClass']);
                if (!in_array($_QET['class'], $TicketsClass)) dies(-1, '参数异常！');
                if (empty($_QET['title']) || empty($_QET['content']) || empty($_QET['time'])) dies(-1, '请提交完整！');
                if ($_QET['order'] <> '不选择相关订单') {
                    $Order = $DB->get('order', '*', ['order' => $_QET['order'], 'uid' => $USERDATA['id']]);
                    if (!$Order) dies(-1, '订单不存在,或此订单非你所有!');
                }

                $Count = $DB->count('tickets', ['uid' => $USERDATA['id'], 'state' => 2, 'type' => [1, 2]]);
                if ($Count > 6) dies(-1, '进行中的工单最多只可同时存在6个！');
                $Res = $DB->insert('tickets', [
                    'uid' => $USERDATA['id'],
                    'order' => $_QET['order'],
                    'name' => $_QET['title'],
                    'content' => $_QET['content'],
                    'class' => $_QET['class'],
                    'timetips' => $_QET['time'],
                    'addtime' => $date,
                ]);

                $ID = $DB->id();

                if ($Res) {
                    if ($_QET['order'] <> '不选择相关订单') {
                        @$DB->update('order', ['state' => 6], ['order' => $_QET['order']]);
                    };

                    Hook::execute('WorkOrderNew', [
                        'uid' => $USERDATA['id'],
                        'order' => $_QET['order'],
                        'name' => $_QET['title'],
                        'content' => $_QET['content'],
                        'class' => $_QET['class'],
                        'timetips' => $_QET['time'],
                        'addtime' => $date,
                    ]);

                    dies(1, '您的工单已经创建成功,分配的工单号为：' . $ID);
                } else dies(-1, '工单创建失败,请联系管理员处理！');
                break;
            default:
                dies(-1, '403');
                break;
        }
        break;
    case 'Mark': //评论管理
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        $DB = SQL::DB();
        switch ($_QET['type']) {
            case 'List':
                $Res = $DB->select('mark', '*', [
                    'ORDER' => [
                        'id' => 'DESC'
                    ],
                    'uid' => $USERDATA['id'],
                    'LIMIT' => [(($_QET['page'] - 1) * $_QET['limit']), $_QET['limit']],
                ]);
                $Count = $DB->count('mark', '*');
                dier([
                    'code' => 0,
                    'msg' => '获取成功',
                    'data' => $Res,
                    'count' => $Count,
                ]);
                break;
        }
        break;
    case 'AlterPrice': //商品价格调整！
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        if ($USERDATA['grade'] < $conf['usergradeprofit']) dies(-1, '您当前等级无法设置商品价格,请先去提升等级吧！');
        test(['gid|e', 'rise|i']);
        if ((float)$_QET['rise'] < 0) dies(-1, '价格涨幅比例不能低于0%！');
        if ((float)$_QET['rise'] > 1000) dies(-1, '价格涨幅比例不能高于1000%！');
        if (empty($_QET['gid']) != -1 && empty($_QET['gid']) < 0) dies(-1, '商品ID有误！');
        $DB = SQL::DB();
        $Deploy = json_decode($USERDATA['pricehike'], TRUE); //商品配置

        if ((int)$_QET['gid'] == -1) {
            /**
             * 调整全部
             */
            $GoodsList = $DB->select('goods', ['gid'], [
                'name[~]' => $_QET['name'],
                'state' => 1
            ]);

            if (count($GoodsList) == 0) dies(-1, '无可改价商品！');
            foreach ($GoodsList as $value) {
                $Deploy[$value['gid']]['rise'] = (float)$_QET['rise'];
            }
            $Msg = '恭喜,您本次成功将' . count($GoodsList) . '个商品的价格涨幅比设置为：' . (float)$_QET['rise'] . '%';
            $log = '用户[' . $USERDATA['id'] . ']于' . $date . '成功将' . count($GoodsList) . '个商品的价格涨幅比设置为：' . (float)$_QET['rise'] . '%';
        } else {
            /**
             * 调整单个
             */
            $Get = $DB->get('goods', ['name', 'state', 'gid'], ['gid' => $_QET['gid']]);
            if (!$Get) dies(-1, '编号为：' . $_QET['gid'] . '的商品不存在！');
            if ($Get['state'] != 1) dies(-1, '编号为：' . $_QET['gid'] . '的商品已经下架！');
            $Deploy[$Get['gid']]['rise'] = (float)$_QET['rise'];

            $Msg = '恭喜,您成功将商品[' . $Get['name'] . ']的价格涨幅比设置为：' . (float)$_QET['rise'] . '%';
            $log = '用户[' . $USERDATA['id'] . ']于' . $date . '将商品[' . $Get['name'] . ']的价格涨幅比设置为：' . (float)$_QET['rise'] . '%';
        }

        $Res = $DB->update('user', [
            'pricehike' => json_encode($Deploy, JSON_UNESCAPED_UNICODE)
        ], [
            'id' => $USERDATA['id']
        ]);

        if ($Res) {
            userlog('商品改价', $log, $USERDATA['id'], (float)$_QET['rise']);
            dies(1, $Msg);
        } else dies(-1, '调整失败！');
        break;
    case 'GoodsState': //调整商品上下架状态
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        if ($USERDATA['grade'] < $conf['usergradegoodsstate']) dies(-1, '您当前等级无法设置商品上下架状态,请先去提升等级吧！');
        test(['gid|e', 'state|e']);
        if ((int)$_QET['state'] != 1 && (int)$_QET['state'] != -1) dies(-1, '状态有误！');
        if (empty($_QET['gid']) != -1 && empty($_QET['gid']) < 0) dies(-1, '商品ID有误！');
        $DB = SQL::DB();
        $Deploy = json_decode($USERDATA['pricehike'], TRUE); //商品配置

        if ((int)$_QET['gid'] == -1) {
            /**
             * 调整全部
             */
            $GoodsList = $DB->select('goods', ['gid'], [
                'name[~]' => $_QET['name'],
                'state' => 1
            ]);

            if (count($GoodsList) == 0) dies(-1, '无可设置商品！');
            foreach ($GoodsList as $value) {
                $Deploy[$value['gid']]['state'] = (int)$_QET['state'];
            }
            $Msg = '恭喜,您本次成功将' . count($GoodsList) . '个商品的状态设置为' . ($_QET['state'] == 1 ? '上架' : '下架');
            $log = '用户[' . $USERDATA['id'] . ']于' . $date . '成功将' . count($GoodsList) . '个商品的状态设置为：' . ($_QET['state'] == 1 ? '上架' : '下架');
        } else {
            /**
             * 调整单个
             */
            $Get = $DB->get('goods', ['name', 'state', 'gid'], ['gid' => $_QET['gid']]);
            if (!$Get) dies(-1, '编号为：' . $_QET['gid'] . '的商品不存在！');
            if ($Get['state'] != 1) dies(-1, '编号为：' . $_QET['gid'] . '的商品已经下架！');
            $Deploy[$Get['gid']]['state'] = (int)$_QET['state'];

            $Msg = '恭喜,您成功将商品[' . $Get['name'] . ']的状态设置为：' . ($_QET['state'] == 1 ? '上架' : '下架');
            $log = '用户[' . $USERDATA['id'] . ']于' . $date . '将商品[' . $Get['name'] . ']的状态设置为：' . ($_QET['state'] == 1 ? '上架' : '下架');
        }

        $Res = $DB->update('user', [
            'pricehike' => json_encode($Deploy, JSON_UNESCAPED_UNICODE)
        ], [
            'id' => $USERDATA['id']
        ]);

        if ($Res) {
            userlog('状态调整', $log, $USERDATA['id'], (float)$_QET['rise']);
            dies(1, $Msg);
        } else dies(-1, '调整失败！');
        break;
    case 'LogList': //获取日志列表
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        test(['page|e', 'uid|e']);

        $DB = SQL::DB();
        $LIMIT = 8;
        $Page = ($_QET['page'] - 1) * $LIMIT;


        if ($_QET['uid'] == -1) {
            $Res = $DB->select('journal', '*', [
                'name[~]' => $_QET['name'],
                'LIMIT' => [$Page, $LIMIT],
                'uid' => $USERDATA['id'],
                'ORDER' => [
                    'id' => 'DESC'
                ]
            ]);

            if (!empty($_QET['name'])) {
                $Count = $DB->count('journal', ['name[~]' => $_QET['name'], 'uid' => $USERDATA['id']]);
            } else $Count = $DB->count('journal', ['uid' => $USERDATA['id']]);
        } else {
            if (!empty($_QET['name'])) {
                $Res = $DB->select('journal', '*', [
                    'name[~]' => $_QET['name'],
                    'content[~]' => `[` . $_QET['uid'] . `]`,
                    'LIMIT' => [$Page, $LIMIT],
                    'uid' => $USERDATA['id'],
                    'ORDER' => [
                        'id' => 'DESC'
                    ]
                ]);
            } else {
                $Res = $DB->select('journal', '*', [
                    'name[~]' => ['货币提成', '余额提成', '升级提成'],
                    'content[~]' => `[` . $_QET['uid'] . `]`,
                    'LIMIT' => [$Page, $LIMIT],
                    'uid' => $USERDATA['id'],
                    'ORDER' => [
                        'id' => 'DESC'
                    ]
                ]);
            }

            if (!empty($_QET['name'])) {
                $Count = $DB->count('journal', ['name[~]' => $_QET['name'], 'uid' => $USERDATA['id'], 'content[~]' => `[` . $_QET['uid'] . `]`]);
            } else $Count = $DB->count('journal', ['uid' => $USERDATA['id'], 'name[~]' => ['货币提成', '余额提成', '升级提成'], 'content[~]' => `[` . $_QET['uid'] . `]`]);
        }

        $Data = [];
        foreach ($Res as $v) {
            if ($v['name'] == '余额提成' || $v['name'] == '货币提成' || $v['name'] == '余额提成(无效)' || $v['name'] == '货币提成(无效)') {
                $v['content'] = explode('！', $v['content'])[0] . '！';
            }
            $Data[] = [
                'id' => $v['id'],
                'name' => $v['name'],
                'ip' => $v['ip'],
                'date' => $v['date'],
                'count' => round($v['count'], 8),
                'content' => $v['content']
            ];
        }

        dier([
            'code' => 1,
            'msg' => '数据获取成功',
            'data' => $Data,
            'count' => $Count
        ]);
        break;
    case 'GoodsList': //获取商品列表
        if ($USERDATA == false) dies(-1, '请先完成登陆！');

        test(['page|e']);

        $DB = SQL::DB();

        $LIMIT = 8;
        $Page = ($_QET['page'] - 1) * $LIMIT;

        $Res = $DB->select(
            'goods',
            '*',
            [
                'state' => 1,
                'name[~]' => $_QET['name'],
                'LIMIT' => [$Page, $LIMIT],
                'ORDER' => [
                    'gid' => 'DESC'
                ]
            ]
        );
        $Data = [];
        $Deploy = json_decode($USERDATA['pricehike'], TRUE); //商品配置
        foreach ($Res as $res) {
            if ($res['specification'] == 2) {
                $SpRule = RlueAnalysis($res['specification_set'], $res, 1, true);
                if ($SpRule == -1) {
                    $price = price::price_uid($USERDATA['grade'], $res['profits'], $res['money'], $res['custom']);
                } else {
                    $SkuData = [
                        'data' => $SpRule,
                    ];
                    $DataRule = $SkuData['data']['Parameter'][0];
                    $price = [
                        'price' => $DataRule['price'],
                        'points' => $DataRule['points'],
                        'level' => $DataRule['level'],
                    ];
                }
            } else {
                $price = price::price_uid($USERDATA['grade'], $res['profits'], $res['money'], $res['custom']);
            }

            $res['method'] = json_decode($res['method'], TRUE);

            if (in_array(2, $res['method']) && in_array(3, $res['method'])) {
                //支持余额+积分
                $res['method'] = 1;
            } else if (in_array(2, $res['method']) && !in_array(3, $res['method'])) {
                //支持余额不支持积分
                $res['method'] = 2;
            } else if (!in_array(2, $res['method']) && in_array(3, $res['method'])) {
                //不支持余额支持积分
                $res['method'] = 3;
            } else {
                //其他
                $res['method'] = 2;
            }
            if ($price['price'] <= 0.01 && $price['price'] <> 0) $price['price'] = 0.01;
            $res['price'] = round($price['price'], 2);
            $res['points'] = round($price['points'], 0);

            if (empty($_SESSION['GIDSALES_' . $res['gid']])) {
                $LSALES = $conf['SalesSum'] + round(($conf['SalesSum'] * (rand(1, 50) / 100)), 0);
                $_SESSION['GIDSALES_' . $res['gid']] = $LSALES;
            } else $LSALES = $_SESSION['GIDSALES_' . $res['gid']];

            $res['sales'] = $DB->sum('order', 'num', ['gid' => $res['gid']]) + $LSALES;

            $Rise = ((float)$Deploy[$res['gid']]['rise'] <= 0 ? 0 : (float)$Deploy[$res['gid']]['rise']);

            $Data[] = [
                'gid' => $res['gid'],
                'name' => $res['name'],
                'image' => ImageUrl($res['image']),
                'method' => $res['method'],
                'price' => $res['price'], //成本
                'points' => $res['points'],
                'quantity' => (int)$res['quantity'],
                'docs' => htmlspecialchars_decode($res['docs']),
                'sales' => $res['sales'],
                'state' => ($Deploy[$res['gid']]['state'] != -1 ? 1 : -1), //商品自定义状态
                'rise' => $Rise  //商品价格涨幅百分比0~100
            ];
        }

        if (!empty($_QET['name'])) {
            $Count = $DB->count('goods', ['state' => 1, 'name[~]' => $_QET['name']]);
        } else $Count = $DB->count('goods', ['state' => 1]);

        dier([
            'code' => 1,
            'data' => $Data,
            'count' => $Count
        ]);
        break;
    case 'SubordinateUserMoney': //查询下级用户带来的收益
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        if ($USERDATA['grade'] < 2) dies(-1, '权限不足！');
        test(['uid|e'], '请将用户ID填写完整！');
        dier([
            'code' => 1,
            'msg' => '获利数据获取成功',
            'data' => SubordinateUserMoney($USERDATA['id'], $_QET['uid'])
        ]);
        break;
    case 'SubordinateUser': //获取下级用户列表
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        if ($USERDATA['grade'] < 2) dies(-1, '权限不足！');
        test(['page|e', 'type|e'], '请填写完整哦！');
        if (!empty($_SESSION['SubordinateUser']) && $_QET['type'] == 1) {
            $Data = $_SESSION['SubordinateUser'];
        } else {
            $Data = SubordinateUser($USERDATA, 1, $USERDATA['id']);
            $_SESSION['SubordinateUser'] = $Data;
        }
        if ($Data == -1) {
            dier([
                'code' => 1,
                'data' => [],
                'count' => 0
            ]);
        } else {
            if ($Data != -1) $Data = array_sort($Data, 'id', 'desc');
            $limit = 8;
            $page = ($_QET['page'] - 1) * $limit;
            $limit = $limit + $page;
            $ArrayData = [];
            for ($i = $page; $i < $limit; $i++) {
                if (empty($Data[$i])) continue;
                $ArrayData[] = $Data[$i];
            }
            dier([
                'code' => 1,
                'data' => $ArrayData,
                'count' => count($Data),
            ]);
        }
        break;
    case 'CouponList': //获取优惠券列表
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        $DB = SQL::DB();
        test(['type|e'], '请提交需要获取的类型');
        $LIMIT = 16;
        $Page = ($_QET['page'] - 1) * $LIMIT;

        $SQL = [
            'LIMIT' => [$Page, $LIMIT],
            'uid' => $USERDATA['id'],
            'ORDER' => [
                'id' => 'DESC'
            ]
        ];


        if ($_QET['type'] == 1) {
            $SQL = array_merge($SQL, ['oid' => -1]);
            $SQLC = [
                'uid' => $USERDATA['id'],
                'oid' => -1,
            ];
        } else {
            $SQL = array_merge($SQL, ['oid[!]' => -1]);
            $SQLC = [
                'uid' => $USERDATA['id'],
                'oid[!]' => -1,
            ];
        }

        if (!empty($_QET['gid'])) {
            $SQL = array_merge($SQL, ['gid' => $_QET['gid']]);
            $SQLC = array_merge($SQLC, ['gid' => $_QET['gid']]);
        }

        if (!empty($_QET['name'])) {
            $SQL = array_merge($SQL, [
                'OR' => [
                    'id[~]' => $_QET['name'],
                    'oid[~]' => $_QET['name'],
                    'token[~]' => $_QET['name'],
                    'ip[~]' => $_QET['name'],
                    'name[~]' => $_QET['name'],
                ]
            ]);

            $SQLC = array_merge($SQLC, [
                'OR' => [
                    'id[~]' => $_QET['name'],
                    'oid[~]' => $_QET['name'],
                    'token[~]' => $_QET['name'],
                    'ip[~]' => $_QET['name'],
                    'name[~]' => $_QET['name'],
                ]
            ]);
        }

        $Res = $DB->select('coupon', '*', $SQL);
        if (count($Res) == 0) dies(-1, '空空如也！');

        $Data = [];
        foreach ($Res as $v) {
            if ($v['term_type'] == 1) {
                $TIME = strtotime($v['gettime']) + (60 * 60 * 24 * $v['indate']);
            } else {
                $TIME = strtotime($v['expirydate']);
            }
            unset($v['uid'], $v['ip'], $v['indate'], $v['expirydate'], $v['get_way'], $v['limit'], $v['limit_token'], $v['addtime']);
            $v['minimum'] = round($v['minimum'], 8);
            $v['money'] = round($v['money'], 8);
            $v['expirydate'] = (($TIME - time()) <= 0 ? '已过期' : Sec2Time($TIME - time()));
            $Data[] = $v;
        }

        $Count = $DB->count('coupon', $SQLC);

        dier([
            'code' => 1,
            'msg' => '数据获取成功',
            'data' => $Data,
            'count' => $Count
        ]);
        break;
    case 'CouponConversion': //兑换优惠券
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        $DB = SQL::DB();
        test(['token|e'], '请提交优惠券 券码!');
        $User = $USERDATA;

        $Coupon = $DB->get('coupon', '*', [
            'token' => $_QET['token'],
            'oid' => -1,
            'uid' => -1,
        ]);

        if (!$Coupon) dies(-1, '您提交的券码可能是无效券码，请核对后再来兑换！');

        $Count = $DB->count('coupon', [
            'limit_token' => $Coupon['limit_token'],
            'uid' => $User['id'],
        ]);

        if ($Count >= $Coupon['limit']) dies(-1, '此批优惠券每个用户最多兑换' . $Coupon['limit'] . '张，无法继续兑换！');

        $CSQL = [
            'uid' => $User['id'],
            'gettime[>]' => $times,
        ];

        if ($conf['CouponUseIpType'] == 1) {
            $CSQL = [
                'OR' => [
                    'uid' => $User['id'],
                    'ip' => userip()
                ],
                'gettime[>]' => $times,
            ];
        }

        $CountUser = $DB->count('coupon', $CSQL);

        if ($CountUser >= $conf['CouponGetMax']) {
            dies(-1, '今日最多可获得' . $conf['CouponGetMax'] . '张优惠券,您已经获得了' . $CountUser . '张,请改日再来');
        }


        $Res = $DB->update('coupon', [
            'uid' => $User['id'],
            'gettime' => $date,
            'ip' => userip()
        ], [
            'id' => $Coupon['id'],
        ]);
        if ($Res) {
            userlog('兑换优惠券', '用户[' . $User['id'] . ']于' . $date . '兑换了优惠券[' . $Coupon['token'] . ']', $User['id'], '0');
            dies(1, '恭喜你兑换成功！');
        } else dies(-1, '抱歉，兑换失败!');
        break;
    default:
        header('HTTP/1.1 404 Not Found');
        dies(-2, '访问路径不存在！');
        break;
}
